package com.colorlight.cloud.complete.entity.instructions;

import com.colorlight.cloud.common.exception.ParameterException;
import com.colorlight.cloud.common.model.ExceptionEnum;
import com.colorlight.cloud.complete.api.CompleteEntityScheduleActions;
import com.colorlight.cloud.complete.entity.po.M2Relay;
import com.colorlight.iot.proto.complete.instruction.CompleteInstruction;
import com.google.protobuf.ByteString;
import com.google.protobuf.InvalidProtocolBufferException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 设置M2继电器状态
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Slf4j
public class SetM2Relay implements CompleteEntityScheduleActions {

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class InputMsg implements Serializable {
        /**
         * 要设置的M2继电器状态
         */
        private List<M2Relay> relay;
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class OutputMsg implements Serializable {
        /**
         * 设置后的M2继电器状态
         */
        private List<M2Relay> relay;
    }

    private InputMsg input;
    private OutputMsg output;

    @Override
    public ByteString objectConvertBytes() {
        final CompleteInstruction.SetM2Relay.InputMsg.Builder inputMsg =
                CompleteInstruction.SetM2Relay.InputMsg.newBuilder();
        SetM2Relay.InputMsg thisInput = this.getInput();
        inputMsg.addAllRelay(thisInput.getRelay().stream().map(M2Relay::toProto).collect(Collectors.toList()));
        final CompleteInstruction.SetM2Relay.Builder builder =
                CompleteInstruction.SetM2Relay.newBuilder();
        builder.setInput(inputMsg);
        return builder.build().toByteString();
    }

    @Override
    public SetM2Relay byteConvertObject(ByteString bytes) {
        CompleteInstruction.SetM2Relay setM2Relay = null;
        try {
            setM2Relay = CompleteInstruction.SetM2Relay.parseFrom(bytes);
        } catch (InvalidProtocolBufferException e) {
            log.error("", e);
        }
        if (Objects.isNull(setM2Relay)) {
            throw new ParameterException(ExceptionEnum.MSG_PARAMETER_EXCEPTION);
        }
        SetM2Relay.OutputMsg outputMsg = new SetM2Relay.OutputMsg();
        CompleteInstruction.SetM2Relay.OutputMsg output = setM2Relay.getOutput();
        List<M2Relay> relay = output.getRelayList().stream()
                .map(proto -> new M2Relay().formProto(proto))
                .collect(Collectors.toList());
        outputMsg.setRelay(relay);
        this.setOutput(outputMsg);
        return this;
    }
}

